package org.example.service.impl;

import org.example.mapper.FriendRelationMapper;
import org.example.mapper.SleepRecordMapper;
import org.example.mapper.UserMapper;
import org.example.pojo.FriendDynamicVO;
import org.example.pojo.SleepRecord;
import org.example.pojo.User;
import org.example.service.FriendDynamicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FriendDynamicServiceImpl implements FriendDynamicService {

    @Autowired
    private FriendRelationMapper friendRelationMapper;

    @Autowired
    private SleepRecordMapper sleepRecordMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<FriendDynamicVO> getFriendDynamics(Long userId) {
        // 1. 获取好友列表
        List<Long> friendIds = friendRelationMapper.selectFriendIds(userId);

        if(CollectionUtils.isEmpty(friendIds)) {
            return Collections.emptyList();
        }

        // 2. 获取好友最新的睡眠记录
        List<SleepRecord> records = sleepRecordMapper.selectLatestRecords(friendIds);

        // 3. 转换为前端展示VO
        return records.stream().map(record -> {
            FriendDynamicVO vo = new FriendDynamicVO();
            
            // 设置用户基本信息
            User user = User.builder()
                    .id(record.getUserId())
                    .build();
            user = userMapper.getUser(user);
            
            vo.setId(user.getId());
            vo.setName(user.getUsername());
            vo.setAvatar(user.getAvatar());

            // 设置睡眠信息
            vo.setSleepTime(record.getSleepTime().format(DateTimeFormatter.ofPattern("HH:mm")) + "入睡");
            vo.setSleepQuality(record.getSleepQuality());

            return vo;
        }).collect(Collectors.toList());
    }
}

